<template>
  <div class="order-detail-container">
    <div class="page-header">
      <el-button @click="$router.go(-1)" icon="ArrowLeft">返回</el-button>
      <h2>订单详情</h2>
    </div>

    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>

    <div v-else-if="orderInfo" class="order-detail-content">
      <!-- 订单状态 -->
      <el-card class="status-card">
        <div class="status-info">
          <div class="status-icon">
            <el-icon :size="48" :color="getStatusColor(orderInfo.order.status)">
              <component :is="getStatusIcon(orderInfo.order.status)" />
            </el-icon>
          </div>
          <div class="status-text">
            <h3>{{ getStatusText(orderInfo.order.status) }}</h3>
            <p>{{ getStatusDescription(orderInfo.order.status) }}</p>
          </div>
          <div class="status-actions">
            <el-button 
              v-if="orderInfo.order.status === 0" 
              type="primary" 
              @click="goToPayment"
              :loading="paying"
            >
              立即支付
            </el-button>
            <el-button 
              v-if="orderInfo.order.status === 0" 
              type="danger" 
              @click="cancelOrder"
              :loading="cancelling"
            >
              取消订单
            </el-button>
            <el-button 
              v-if="orderInfo.order.status === 2" 
              type="success" 
              @click="completeOrder"
              :loading="completing"
            >
              确认收货
            </el-button>
          </div>
        </div>
      </el-card>

      <!-- 订单信息 -->
      <el-card class="info-card">
        <template #header>
          <div class="card-header">
            <span>订单信息</span>
          </div>
        </template>
        
        <div class="order-info">
          <div class="info-row">
            <span class="label">订单号：</span>
            <span class="value">{{ orderInfo.order.orderNumber }}</span>
          </div>
          <div class="info-row">
            <span class="label">创建时间：</span>
            <span class="value">{{ formatDate(orderInfo.order.createTime) }}</span>
          </div>
          <div class="info-row" v-if="orderInfo.order.paymentTime">
            <span class="label">支付时间：</span>
            <span class="value">{{ orderInfo.order.paymentTime }}</span>
          </div>
          <div class="info-row" v-if="orderInfo.order.shippingTime">
            <span class="label">发货时间：</span>
            <span class="value">{{ orderInfo.order.shippingTime }}</span>
          </div>
          <div class="info-row" v-if="orderInfo.order.completionTime">
            <span class="label">完成时间：</span>
            <span class="value">{{ orderInfo.order.completionTime }}</span>
          </div>
          <div class="info-row" v-if="orderInfo.order.cancellationTime">
            <span class="label">取消时间：</span>
            <span class="value">{{ orderInfo.order.cancellationTime }}</span>
          </div>
          <div class="info-row" v-if="orderInfo.order.cancelReason">
            <span class="label">取消原因：</span>
            <span class="value cancel-reason">{{ orderInfo.order.cancelReason }}</span>
          </div>
          <div class="info-row" v-if="orderInfo.order.paymentMethod !== null">
            <span class="label">支付方式：</span>
            <span class="value">{{ getPaymentMethodText(orderInfo.order.paymentMethod) }}</span>
          </div>
        </div>
      </el-card>

      <!-- 商品信息 -->
      <el-card class="products-card">
        <template #header>
          <div class="card-header">
            <span>商品信息</span>
          </div>
        </template>
        
        <div class="products-list">
          <div v-for="item in orderInfo.items" :key="item.id" class="product-item">
            <div class="product-image">
              <img 
                :src="item.productImage || '/default-product.jpg'" 
                :alt="item.productName"
                @click="viewProduct(item.productId)"
              />
            </div>
            <div class="product-info">
              <div class="product-name" @click="viewProduct(item.productId)">
                {{ item.productName }}
              </div>
              <div class="product-price">¥{{ item.price }}</div>
            </div>
            <div class="product-quantity">
              <span>x{{ item.quantity }}</span>
            </div>
            <div class="product-subtotal">
              ¥{{ (item.price * item.quantity).toFixed(2) }}
            </div>
          </div>
        </div>
        
        <div class="order-total">
          <div class="total-row">
            <span>商品总额：</span>
            <span>¥{{ orderInfo.order.totalPrice }}</span>
          </div>
          <div class="total-row">
            <span>运费：</span>
            <span>¥0.00</span>
          </div>
          <div class="total-row total-price">
            <span>实付金额：</span>
            <span>¥{{ orderInfo.order.totalPrice }}</span>
          </div>
        </div>
      </el-card>

      <!-- 收货地址 -->
      <el-card class="address-card">
        <template #header>
          <div class="card-header">
            <span>收货地址</span>
          </div>
        </template>
        
        <div v-if="orderInfo.address" class="address-info">
          <div class="address-row">
            <span class="label">收货人：</span>
            <span class="value">{{ orderInfo.address.receiverName }}</span>
          </div>
          <div class="address-row">
            <span class="label">联系电话：</span>
            <span class="value">{{ orderInfo.address.phone }}</span>
          </div>
          <div class="address-row">
            <span class="label">收货地址：</span>
            <span class="value">
              {{ orderInfo.address.province }} {{ orderInfo.address.city }} {{ orderInfo.address.district }} {{ orderInfo.address.detailAddress }}
            </span>
          </div>
        </div>
      </el-card>
    </div>

    <div v-else class="error-container">
      <el-empty description="订单不存在或已被删除" />
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
  ArrowLeft, 
  Clock, 
  CircleCheck, 
  Van, 
  Check, 
  Close,
  Wallet,
  CreditCard
} from '@element-plus/icons-vue';
import request from '@/utils/request';

export default {
  name: 'OrderDetailPage',
  components: {
    ArrowLeft,
    Clock,
    CircleCheck,
    Van,
    Check,
    Close,
    Wallet,
    CreditCard
  },
  setup() {
    const route = useRoute();
    const router = useRouter();
    
    const orderInfo = ref(null);
    const loading = ref(false);
    const paying = ref(false);
    const cancelling = ref(false);
    const completing = ref(false);

    const fetchOrderDetail = async () => {
      const orderId = route.params.orderId;
      if (!orderId) {
        ElMessage.error('订单ID不能为空');
        router.push('/orders');
        return;
      }

      loading.value = true;
      try {
        const response = await request.get(`/orders/${orderId}`, {
          params: { userId: localStorage.getItem('userId') }
        });
        
        if (response.code === 200) {
          orderInfo.value = response.data;
        } else {
          ElMessage.error(response.message || '获取订单详情失败');
        }
      } catch (error) {
        ElMessage.error('获取订单详情失败');
      } finally {
        loading.value = false;
      }
    };

    const getStatusText = (status) => {
      const statusMap = {
        0: '待支付',
        1: '已支付',
        2: '已发货',
        3: '已完成',
        4: '已取消'
      };
      return statusMap[status] || '未知状态';
    };

    const getStatusDescription = (status) => {
      const descMap = {
        0: '请尽快完成支付，超时订单将自动取消',
        1: '订单已支付，商家正在处理中',
        2: '商品已发货，请注意查收',
        3: '订单已完成，感谢您的购买',
        4: '订单已取消'
      };
      return descMap[status] || '';
    };

    const getStatusIcon = (status) => {
      const iconMap = {
        0: 'Clock',
        1: 'CircleCheck',
        2: 'Van',
        3: 'Check',
        4: 'Close'
      };
      return iconMap[status] || 'Clock';
    };

    const getStatusColor = (status) => {
      const colorMap = {
        0: '#e6a23c',
        1: '#409eff',
        2: '#909399',
        3: '#67c23a',
        4: '#f56c6c'
      };
      return colorMap[status] || '#909399';
    };

    const getPaymentMethodText = (method) => {
      const methodMap = {
        0: '支付宝',
        1: '微信支付'
      };
      return methodMap[method] || '未知';
    };

    const formatDate = (dateString) => {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN');
    };

    const goToPayment = () => {
      router.push(`/payment/${orderInfo.value.order.id}`);
    };

    const cancelOrder = async () => {
      try {
        // 显示取消原因输入对话框
        const { value: cancelReason } = await ElMessageBox.prompt(
          '请输入取消订单的原因：',
          '取消订单',
          {
            confirmButtonText: '确定取消',
            cancelButtonText: '取消',
            inputType: 'textarea',
            inputPlaceholder: '请详细说明取消原因...',
            inputValidator: (value) => {
              if (!value || value.trim().length === 0) {
                return '取消原因不能为空';
              }
              if (value.trim().length < 5) {
                return '取消原因至少需要5个字符';
              }
              if (value.trim().length > 200) {
                return '取消原因不能超过200个字符';
              }
              return true;
            },
            inputErrorMessage: '请输入有效的取消原因',
            type: 'warning'
          }
        );

        cancelling.value = true;
        const response = await request.post(`/orders/${orderInfo.value.order.id}/cancel`, null, {
          params: { 
            userId: localStorage.getItem('userId'),
            role: localStorage.getItem('role'),
            cancelReason: cancelReason.trim()
          }
        });
        
        if (response.code === 200) {
          ElMessage.success('订单已成功取消');
          fetchOrderDetail();
        } else {
          ElMessage.error(response.message || '取消失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('取消失败: ' + (error.response?.data?.message || '网络错误'));
        }
      } finally {
        cancelling.value = false;
      }
    };

    const completeOrder = async () => {
      try {
        await ElMessageBox.confirm('确认已收到商品吗？', '确认收货', {
          confirmButtonText: '确认收货',
          cancelButtonText: '取消',
          type: 'warning'
        });

        completing.value = true;
        const response = await request.post(`/orders/${orderInfo.value.order.id}/complete`, null, {
          params: { userId: localStorage.getItem('userId') }
        });
        
        if (response.code === 200) {
          ElMessage.success('订单已完成');
          fetchOrderDetail();
        } else {
          ElMessage.error(response.message || '操作失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('操作失败: ' + (error.response?.data?.message || '网络错误'));
        }
      } finally {
        completing.value = false;
      }
    };

    const viewProduct = (productId) => {
      if (productId) {
        router.push(`/product/${productId}`);
      }
    };

    onMounted(() => {
      fetchOrderDetail();
    });

    return {
      orderInfo,
      loading,
      paying,
      cancelling,
      completing,
      getStatusText,
      getStatusDescription,
      getStatusIcon,
      getStatusColor,
      getPaymentMethodText,
      formatDate,
      goToPayment,
      cancelOrder,
      completeOrder,
      viewProduct
    };
  }
};
</script>

<style scoped>
.order-detail-container {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  gap: 15px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.loading-container {
  padding: 40px;
}

.error-container {
  text-align: center;
  padding: 60px 20px;
}

.status-card {
  margin-bottom: 20px;
}

.status-info {
  display: flex;
  align-items: center;
  gap: 20px;
}

.status-icon {
  flex-shrink: 0;
}

.status-text {
  flex: 1;
}

.status-text h3 {
  margin: 0 0 5px 0;
  color: #303133;
}

.status-text p {
  margin: 0;
  color: #909399;
}

.status-actions {
  display: flex;
  gap: 10px;
}

.info-card,
.products-card,
.address-card {
  margin-bottom: 20px;
}

.card-header {
  font-weight: 600;
  color: #303133;
}

.order-info {
  padding: 10px 0;
}

.info-row {
  display: flex;
  margin-bottom: 15px;
}

.info-row .label {
  width: 100px;
  color: #909399;
  flex-shrink: 0;
}

.info-row .value {
  color: #303133;
  font-weight: 500;
}

.products-list {
  margin-bottom: 20px;
}

.product-item {
  display: flex;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
}

.product-item:last-child {
  border-bottom: none;
}

.product-image {
  width: 60px;
  height: 60px;
  margin-right: 15px;
  cursor: pointer;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.product-info {
  flex: 1;
  margin-right: 15px;
}

.product-name {
  font-weight: 600;
  color: #303133;
  margin-bottom: 5px;
  cursor: pointer;
}

.product-name:hover {
  color: #409eff;
}

.product-price {
  color: #909399;
  font-size: 14px;
}

.product-quantity {
  width: 80px;
  text-align: center;
  color: #606266;
}

.product-subtotal {
  width: 100px;
  text-align: right;
  font-weight: bold;
  color: #f56c6c;
}

.order-total {
  border-top: 1px solid #ebeef5;
  padding-top: 20px;
}

.total-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  color: #606266;
}

.total-price {
  font-size: 18px;
  font-weight: bold;
  color: #f56c6c;
  border-top: 1px solid #ebeef5;
  padding-top: 10px;
  margin-top: 10px;
}

.address-info {
  padding: 10px 0;
}

.address-row {
  display: flex;
  margin-bottom: 15px;
}

.address-row .label {
  width: 100px;
  color: #909399;
  flex-shrink: 0;
}

.address-row .value {
  color: #303133;
  flex: 1;
}

.cancel-reason {
  color: #f56c6c;
  font-style: italic;
  word-break: break-all;
  line-height: 1.4;
}
</style> 